<template>
  <!--pos设备管理-->
  <el-row style="height:100%">
    <page>
      <pageheader :isShow="false">
        pos设备管理
      </pageheader>
      <div class="page-content">
        <el-card class="box-card tag-card">
          <el-row>
            <Cascader :value.sync="ruleForm.company_id_arr"
                      :options="companyOptions"
                      :changeEvent="'companyChange'"
                      :width="'300px'"
                      :isClearable="false">所属企业：</Cascader>
            <span style="margin-left: 20px">所属案场：</span>
            <el-select v-model="ruleForm.case_info_id" collapse-tags filterable placeholder="请选择案场"
                       @visible-change="changeCaseInfo" @remove-tag="removeTag" @change="CaseChange"
                       size="small" multiple clearable style="width:400px">
              <el-option
                v-for="item in caseInfoOptions"
                :key="item.id"
                :label="item.case_name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-row>
          <el-row>
            <span>搜索类型:</span>
            <el-radio-group v-model="ruleForm.search_type" @change="searchChange">
              <el-radio label="1">定向搜索</el-radio>
              <el-radio v-if="buttonPermissions.isUnmounted" label="2">未挂载任何案场</el-radio>
              <el-radio v-if="buttonPermissions.isAll" label="3">全部</el-radio>
            </el-radio-group>
            <span style="margin-left: 20px">是否在线：</span>
            <el-select v-model="ruleForm.isOnline" @change="isOnlineChange"
                       size="small" style="width:200px">
              <el-option label="全部" value=''></el-option>
              <el-option label="在线" value=1></el-option>
              <el-option label="离线" value=0></el-option>
            </el-select>
            <SearchInput style="margin-left: 20px"
                         @deviceSearch="deviceSearch"
                         :searchEvent="'deviceSearch'"
                         :value.sync="keywords"
                         :searchText="'POS编号、api编号、api类型'"
                         ref="clearText"
            >搜索：
            </SearchInput>
          </el-row>
          <el-table :data="dataTable" size="small" stripe>
            <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="60"></el-table-column>
            <el-table-column label="POS编号" prop="pos_code" align="center" sortable></el-table-column>
           <el-table-column prop="case_name" label="所属案场名称" align="center" sortable>
              <template slot-scope="scope">
                {{scope.row.is_bind_case == 1?scope.row.case_name:''}}
                <el-tag v-if="scope.row.is_bind_case != 1" size="mini" type="warning">未挂载</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="api编号" prop="api_code" align="center" sortable></el-table-column>
            <el-table-column label="api类型" prop="api_type" align="center" sortable></el-table-column>
            <el-table-column label="描述" prop="pos_info" align="center" sortable></el-table-column>
            <el-table-column label="table_code" prop="table_code" align="center" sortable></el-table-column>
            <el-table-column label="设备在线状态" prop="isOnlineName" align="center" width="120px">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.is_online == 1" size="mini" type="success">在线</el-tag>
                <el-tag v-else size="mini" type="danger">离线</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="最后数据时间" prop="last_data_time" align="center" sortable></el-table-column>
            <el-table-column label="最后活跃时间" prop="last_active_time" align="center" sortable></el-table-column>
          </el-table>
          <el-pagination background
                         layout="total,sizes,prev,pager,next"
                         @current-change="currentChange"
                         @size-change="sizeChange"
                         :page-sizes="pagination.pageSizes"
                         :page-size.sync="pagination.pageSize"
                         :total="pagination.total"
                         :current-page.sync="pagination.currentPage"
                         class="paging fr">
          </el-pagination>
        </el-card>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .page-content {
    .tag-card{
      >.el-card__body{
        >.el-row{
          margin-bottom: 12px;
        }
      }
    }
    padding: 15px;
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
    .tag-search{
      width: 40%;
      display: inline-block;
    }
    .tag-search .search-input{
      width: 300px;
      display: inline-block;
    }
    .tag-search .tag-name{
      font-size: 14px;
    }
  }
</style>
<script>
  import page from "@/components/page/page";
  import pageheader from "@/components/page/pageheader";
  import TreeTable from "@/components/common/treeTable";
  import SearchInput from "@/components/sys/assembly/searchinput";
  import Cascader from "@/components/sys/assembly/elcascader";
  export default {
    data() {
      return {
        pageTitle: "设备管理",
        companyOptions:[],//企业列表
        caseInfoOptions:[],//案场列表
        searchOption:[
          {label:'定向搜索',value:1},
          {label:'未挂载任何案场',value:2},
          {label:'全部',value:3},
        ],
        ruleForm:{
          company_id_arr:[],
          company_id:'',
          case_info_id:[],
          search_type:'1',//搜索类型
          isOnline:'',//在线状态
        },
        allCaseArr:[],//全部id
        dataTable:[],
        keywords:'',
        pagination:{
          total:0,//总条目数
          currentPage:1,//当前页数
          pageSize:10,//每页显示条目个数
          pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
        },//表格分页参数
        isAllCase:true,//是否全选
        buttonPermissions:{
          isAll:false,
          isUnmounted:false,
        },

      }
    },
    inject: ["reload"],
    components: {
      page,
      pageheader,
      SearchInput,//搜索框组件
      Cascader,//级联选择器组件
    },
    created() {
      this.getCompanyTree();
      if (sessionStorage.buttonPermissions) {
        this.configPermissions(JSON.parse(sessionStorage.buttonPermissions))
      }
    },
    mounted() {
      //选择所属企业change事件
      this.$Bus.$on('companyChange',data =>{
        this.ruleForm.case_info_id = [];
        this.ruleForm.company_id_arr = data;
        this.ruleForm.company_id = data.slice(-1)[0];
        this.$Bus.$emit('Loading',true);
        this.getCaseInfo(this.ruleForm.company_id)//获取案场列表
      });
    },
    beforeDestroy(){
      this.$Bus.$off('companyChange')
    },
    methods: {
      //配置按钮权限，根据权限不同调整表头渲染参数
      configPermissions(val){
        let buttonPermissions = val
        let menuButtonPermissions = [];//按钮权限数组
        buttonPermissions.forEach(e =>{
          for(let key in e){
            if(key == 'menu_code'){
              menuButtonPermissions.push(e[key])
            }
          }
        });
        this.buttonPermissions.isAll = menuButtonPermissions.includes('isAll') ? true : false;
        this.buttonPermissions.isUnmounted = menuButtonPermissions.includes('isUnmounted') ? true : false;
      },
      //表格序号显示方法
      indexMethod(index){
        return index + ((this.pagination.currentPage - 1) * this.pagination.pageSize) + 1
      },
      //获取企业树
      getCompanyTree(){
        let url = '/sys/report_assist_new/company_tree';
        this.$api.get(url)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          if(data){
            recursion(data.data);
            function recursion(val) {
              if(val.length){
                for(let i in val){
                  val[i].value = val[i].id;
                  val[i].label = val[i].company_name;
                  val[i].parent_id_str = val[i].parent_name_list.join('/');
                  if(val[i].children && val[i].children.length){
                    recursion(val[i].children)
                  }else{
                    delete val[i].children
                  }
                }
              }
            }
            this.companyOptions = data.data;
            this.ruleForm.company_id = data.data[0].id;
            this.ruleForm.company_id_arr.push(data.data[0].id);
            this.getCaseInfo(data.data[0].id)
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.companyOptions = [];
          this.$Bus.$emit('Loading',false)
        })
      },
      //获取案场列表
      getCaseInfo(id){
        let url = '/sys/report_assist_new/case_list';
        let parmas={
          org_id_list:Array.of(id),
          org_type:1
        }
        this.$api.post(url,parmas)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          //判断接口返回正常
          if(data){
            this.caseInfoOptions = data.data;
            this.caseInfoOptions.unshift({case_name:'全部',id:'all'});
            this.ruleForm.case_info_id = ['all']
            this.allCaseArr = this.caseInfoOptions.map(x=>{
              return x.id
            });
            this.allCaseArr = this.allCaseArr.filter(x=>{
              return x != 'all'
            });
            this.isAllCase = true;
            this.getDevice()
          }else{
            this.caseInfoOptions = [];
            this.$Bus.$emit('Loading',false);
          }
        })
        .catch(err=>{
           console.log(err);
          this.caseInfoOptions = [];
          this.$Bus.$emit('Loading',false)
        })
      },
      getDevice(keywords = '',page='',page_size='10'){
        let url = '/sys/pos/search_pos?is_online=' + this.ruleForm.isOnline +
          '&keywords=' + encodeURIComponent(keywords) + '&page='+ page + '&page_size=' + page_size +
          '&search_type=' + this.ruleForm.search_type
        let parmas = {
          case_info_id_list:this.isAllCase ? this.allCaseArr : this.ruleForm.case_info_id
        }
        this.$api.post(url,parmas)
        .then(data => {
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            this.$Bus.$emit('Loading',false);
            return
          }
          //判断接口返回正常
          if(data){
            let _data = data.data
            _data.dataList = _data.dataList.map(x=>{
              if(x.last_data_time){
                x.last_data_time = String(x.last_data_time)
                x.last_data_time = x.last_data_time.substring(0,4) + '-' + x.last_data_time.substring(4,6) + '-' +
                  x.last_data_time.substring(6,8) + ' '+ x.last_data_time.substring(8,10) + ':' +  x.last_data_time.substring(10,12) + ':' + x.last_data_time.substring(12,14)
              }
              if(x.last_active_time){
                x.last_active_time = String(x.last_active_time)
                x.last_active_time = x.last_active_time.substring(0,4) + '-' + x.last_active_time.substring(4,6) + '-' +
                  x.last_active_time.substring(6,8) + ' '+ x.last_active_time.substring(8,10) + ':' +  x.last_active_time.substring(10,12) + ':' + x.last_active_time.substring(12,14)
              }
              return x
            });
            this.dataTable =  _data.dataList
            this.pagination.total = _data.dataCount;
            this.pagination.currentPage = _data.pageCode;
            this.pagination.pageSize = _data.pageSize;
          }else{
            this.dataTable = []
          }
          this.$Bus.$emit('Loading',false)
        })
        .catch(err=>{
           console.log(err);
          this.dataTable = []
          this.$Bus.$emit('Loading',false)
        })
      },
      //每页显示条目个数change事件
      sizeChange(val){
        this.$Bus.$emit('Loading',true)
        this.getDevice(this.keywords,this.pagination.currentPage,val,)
      },
      //分页change事件
      currentChange(val){
        this.$Bus.$emit('Loading',true)
        this.getDevice(this.keywords,val,this.pagination.pageSize)
      },
      //搜索按钮点击事件
      deviceSearch(data) {
        this.$Bus.$emit('Loading',true)
        this.keywords = data;
        this.getDevice(data,'',this.pagination.pageSize)
      },
      //选择案场change
      changeCaseInfo(val){
        if(!val){
          this.getDevice();
        }
      },
      CaseChange(val){
        //已经选择了全部，想要排除掉all这个选项
        if(val[0] == 'all' && val.length != 1){
          this.ruleForm.case_info_id = this.ruleForm.case_info_id.filter(x=>x != 'all')
          this.isAllCase = false
        }else if(val.includes('all')){//点击了全部，干掉其他选中的部分
          this.ruleForm.case_info_id = ['all'];
          this.isAllCase = true;
        }else{
          this.isAllCase = false
        }
      },
      //移除案场选项时
      removeTag(){
        if(this.ruleForm.case_info_id.length==0) {
          this.$message.warning('请至少选择一个案场!');
          this.caseFirstTry()
          return
        }
        this.getDevice()
      },
      

      caseFirstTry(){
        this.ruleForm.case_info_id = ['all']
        this.isAllCase = true;
        this.getDevice();
      },
      //搜索类型change
      searchChange(){
        this.getDevice(this.keywords,'',this.pagination.pageSize)
      },
      //是否在线change
      isOnlineChange(){
        this.$Bus.$emit('Loading',true);
        this.getDevice(this.keywords,'',this.pagination.pageSize)
      }
    },
    watch: {}
  }
</script>
